<?php

class PersonTaskController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
//            array('allow', // allow all users to perform 'index' and 'view' actions
//                'actions' => array('index', 'view'),
//                'users' => array('*'),
//            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'index', 'view', 'assignTaskAjax', 'removeTaskAjax', 'popView'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'morningReport', 'TemplateList', 'eveningReport', 'job'),
                'users' => User::model()->getUsers(1),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * 弹出窗显示personTask
     */
    public function actionPopView($id) {
        $this->layout = 'pop';
        $t = (int) $_GET['t'];
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PersonTask'])) {
            $model->attributes = $_POST['PersonTask'];
            if ($model->save()) {
                $model = $this->loadModel($id);
                $msg = '记录更新成功';
                //记录更新成功后需要判断当前的job是不是所有的task都完成了，如果都完成了，直接关闭job
                $this->autoCloseJob($model->pdid);
            } else {
                $msg = '记录更新失败';
            }
        }
        
        $users = User::model()->findAll();
        $userArr = array();
        foreach($users as $user){
            $userArr[$user['id']] =$user['username'];
        }
        
        if (!$model->transactor) {
            $model->transactor = Yii::app()->user->id;
        }

        $this->render('popUpdate', array(
            'model' => $model,
            'msg' => $msg,
            'type' => $t,
            'users' => $userArr,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new PersonTask;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PersonTask'])) {
            $model->attributes = $_POST['PersonTask'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->ptid));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PersonTask'])) {
            $model->attributes = $_POST['PersonTask'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->ptid));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
//        $dataProvider = new CActiveDataProvider('PersonTask');
//        $this->render('index', array(
//            'dataProvider' => $dataProvider,
//        ));
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
//        $model = new PersonTask('search');
        $model = new TaskItem('search');
        $model->unsetAttributes();  // clear any default values        
        if (isset($_GET['TaskItem']))
            $model->attributes = $_GET['TaskItem'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = PersonTask::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'person-task-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAssignTaskAjax() {
        if (Yii::app()->request->isPostRequest) {
            $criteria = new CDbCriteria;

            $criteria->addInCondition('id', $_POST['taskSelect']);

            $taskIdArr = $_POST['taskSelect'];
            $pdId = $_POST['pdid'];
            if ($taskIdArr && is_numeric($pdId)) {
                $msg = '';
                foreach ($taskIdArr as $idItem) {
                    $personTask = PersonTask::model()->find('pdid=:pdID and tid=:taskID', array('pdID' => (int) $pdId, ':taskID' => (int) $idItem));
                    if (!$personTask) {
                        $task = Task::model()->findByPk((int) $idItem);
                        if ($task) {
                            $model = new PersonTask;
                            $data = array();
                            $data['pdid'] = $pdId;
                            $data['tid'] = $task['taskid'];
                            $data['total_complete'] = $task['complete'];
                            $model->attributes = $data;
                            if ($model->save()) {
                                $msg .= '任务：' . $task['task'] . '(ID:' . $task['taskid'] . ')加入成功
';
                            } else {
                                $msg .= '任务：' . $task['task'] . '(ID:' . $task['taskid'] . ')加入失败
';
                            }
                        }
                    } else {
                        $msg .= '任务ID:' . $idItem . '已存在，不允许重复加入，已跳过
';
                    }
                    unset($personTask);
                    unset($task);
                }
            }

            if (isset(Yii::app()->request->isAjaxRequest)) {
                echo CJSON::encode(array('success' => true, 'msg' => $msg));
            } else {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionRemoveTaskAjax() {
        if (Yii::app()->request->isPostRequest) {
            $taskIdArr = $_POST['taskSelect'];
            $pdId = $_POST['pdid'];
            if ($taskIdArr && is_numeric($pdId)) {
                $msg = '';
                foreach ($taskIdArr as $idItem) {
                    $personTask = PersonTask::model()->find('pdid=:pdID and tid=:taskID', array('pdID' => (int) $pdId, ':taskID' => (int) $idItem));
                    if ($personTask) {
                        if ($personTask['status'] == 0) {
                            if ($this->loadModel($personTask['ptid'])->delete()) {
                                $msg .= '任务：' . $personTask->task->task . '(ID:' . $personTask->task->taskid . ')解除关联成功
';
                            } else {
                                $msg .= '任务：' . $personTask->task->task . '(ID:' . $personTask->task->taskid . ')解除关联失败
';
                            }
                        } else {
                            $msg .= '任务：' . $personTask->task->task . '(ID:' . $personTask->task->taskid . ')已经完成，不能删除
';
                        }
                    } else {
                        $msg .= '任务ID:' . $idItem . '没有关联，不需要删除，已跳过
';
                    }
                    unset($personTask);
                }
            }

            if (isset(Yii::app()->request->isAjaxRequest)) {
                echo CJSON::encode(array('success' => true, 'msg' => $msg));
            } else {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    //template list和personDate的admin类似，只是需要显示出所有的template
    public function actionTemplateList() {
        $model = new PersonDate('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['PersonDate'])) {
            $model->attributes = $_GET['PersonDate'];
        }
        $jobStatus = (int) $_REQUEST['s'];
        $this->render('admin', array(
            'model' => $model,
            'jobStatus' => $jobStatus,
            'title' => $title,
        ));
    }

    //晨报发信，安排今天的工作
    public function actionMorningReport() {
        $office = Yii::app()->params['nowOffice'];
        $officeEmails = Yii::app()->params['officeEmail'];
        $stime = strtotime(date('Y-m-d')); //开始时间
        $etime = strtotime(date('Y-m-d')) + 3600 * 24; //截止时间
        $criteria = new CDbCriteria;
        $criteria->compare('time', '<=' . $stime);
        $criteria->addCondition("pdstatus=0");
        $criteria->addCondition("uoffice='" . $office . "'");
        $criteria->order = 'username ASC'; //排序条件  
        $result = TaskItem::model()->findAll($criteria);

        //把任务按照人员分拣出来
        foreach ($result as $taskItem) {
            $officeReport[$office][$taskItem->username][$taskItem->job][$taskItem->ptid] = $taskItem;
        }

        unset($result);
        unset($criteria);
        //组成信件主体
        $emailInfos = array();
        if ($officeReport) {
            foreach ($officeReport as $key => $reportItem) {
                $emailInfo['email'] = $officeEmails[$key];
                $emailInfo['title'] = $key . ' - To Paul - ' . $key . 'Task List Morning - ' . date("Ymd");
                foreach ($reportItem as $user => $peopleItem) {
                    $people .= $user . ' ';
                    $peopleContent .= $user . ':<br><br>' . chr(13);
                    $peopleContent .= '<table cellspacing="0" cellpadding="0" width="800">
	<tr class="head">
            <td width="25%">Job</td>
            <td>Task</td>
	</tr>'
                    ;
                    $cssClass = array('odd', 'even');
                    $j = 0;
                    foreach ($peopleItem as $jobKey => $jobItem) {
                        $i = 0;
                        $tdClass = $cssClass[$j % 2];
                        foreach ($jobItem as $taskKey => $taskItem) {
                            $peopleContent .= '<tr class="' . $tdClass . '">' . chr(13);
                            if ($i == 0) {
                                $peopleContent .= '<td rowspan="' . count($jobItem) . '">' . $jobKey . '</td>' . chr(13);
                            }
                            $peopleContent .= '<td>' . $taskItem->taskdetail . '(' . $taskKey . ')</td>' . chr(13);
                            $peopleContent .= '</tr>' . chr(13);
                            $i++;
                        }
                        $j++;
                    }
                    $peopleContent .= '</table><br><br>';
                }
                $content = '<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>morning report</title>
<style>
td {
	border:solid #68BADA;
	border-width:0px 1px 1px 0px;
	padding:5px;
}
table {
	border:solid #68BADA;
	border-width:1px 0px 0px 1px;
}
.odd{
	background:none repeat scroll 0 0 #E5F1F4;
}
.even{
	background:none repeat scroll 0 0 #F8F8F8;
}
.head{
	background:none repeat scroll 0 0 #90D8F0;
}
</style>
</head>
<body>';
                $content .= 'Dear Paul,<br><br>' . chr(13);
                $content .= date("m/d/Y") . '当班人员: ' . $people . ' 具体工作如下：<br><br>' . chr(13);
                $content .= $peopleContent . '
谢谢。<br><br>

Task Management System
</body>
</html>
';
                $emailInfo['content'] = $content;
                $emailInfos[$key] = $emailInfo;
                unset($people);
                unset($peopleContent);
                unset($content);
                unset($emailInfo);
            }
        } else {
            $resultMsg = "没有任何人员数据！";
        }
        //开始发信
        if ($emailInfos) {
            foreach ($emailInfos as $key => $emailInfo) {
                $result = $this->sentEmail($emailInfo['email'], $emailInfo['title'], $emailInfo['content']);
                if ($result['result']) {
                    $resultMsg .= $key . '部门晨报发送成功.<br>';
                } else {
                    $resultMsg .= $key . '部门晨报发送出错：' . $result['error'] . '.<br>';
                }
            }
        }
        $this->render('message', array(
            'msg' => $resultMsg,
        ));
    }

    //判断是否超时的工作
    protected function expireTask($office='') {
        $criteria = new CDbCriteria;
        $criteria->addCondition("status=0");
        if ($office) {
            $criteria->with = 'user'; //调用relations
            $criteria->addCondition("user.office='" . $office . "'");
        }
        $jobs = PersonDate::model()->findAll($criteria);
        $expireJobs = array();
        foreach ($jobs as $job) {
            switch ($job->type) {
                case 'S':
                    if (!Time::isLaterThanToday($job->time)) {
                        $expireTasks['S'][] = $job;
                        $jobStr .= $job->job . '<br>';
                    }
                    break;
                case 'O':
                    if (!Time::isLaterThanToday($job->time)) {
                        $expireTasks['O'][] = $job;
                        $jobStr .= $job->job . '<br>';
                    }
                    break;
                case 'D':
                    if (!Time::isLaterThanToday($job->time)) {
                        $expireTasks['D'][] = $job;
                        $jobStr .= $job->job . '<br>';
                    }
                    break;
                case 'W':
                    if (!Time::isThisWeek(strtotime($job->time)) && !Time::isLaterThanToday($job->time)) {
                        $expireTasks['W'][] = $job;
                        $jobStr .= $job->job . '<br>';
                    }
                    break;
                case 'M':
                    if (!Time::isThisMonth(strtotime($job->time)) && !Time::isLaterThanToday($job->time)) {
                        $expireTasks['M'][] = $job;
                        $jobStr .= $job->job . '<br>';
                    }
                    break;
                case 'Y':
                    if (!Time::isThisYear(strtotime($job->time)) && !Time::isLaterThanToday($job->time)) {
                        $expireTasks['Y'][] = $job;
                        $jobStr .= $job->job . '<br>';
                    }
                    break;
                default:
            }
        }
        return $jobStr;
    }

    //晚报发信，汇报今天的工作
    public function actionEveningReport() {
        $office = Yii::app()->params['nowOffice'];
        $officeEmails = Yii::app()->params['officeEmail'];
        $stime = strtotime(date('Y-m-d')); //开始时间
        $etime = strtotime(date('Y-m-d')) + 3600 * 24; //截止时间
        $expireTask = $this->expireTask($office);
        if (!$expireTask) {//没有逾期没有关闭的job
            $criteria = new CDbCriteria;
            $criteria->compare('pdupdated', '>=' . $stime);
            $criteria->compare('pdupdated', '<' . $etime);
            $criteria->addCondition("pdstatus=1");
            $criteria->addCondition("uoffice='" . $office . "'");
            $criteria->order = 'username ASC'; //排序条件
            $result = TaskItem::model()->findAll($criteria);

            //把任务按照人员分拣出来
            foreach ($result as $taskItem) {
                $officeReport[$office][$taskItem->username][$taskItem->job][$taskItem->ptid] = $taskItem;
            }
            unset($result);
            unset($criteria);
            //组成信件主体
            $emailInfos = array();
            if ($officeReport) {
                foreach ($officeReport as $key => $reportItem) {
                    $emailInfo['email'] = $officeEmails[$key];
                    $emailInfo['title'] = $key . ' - To Paul - ' . $key . 'Task List Evening - ' . date("Ymd");
                    foreach ($reportItem as $user => $peopleItem) {
                        $people .= $user . ' ';
                        $peopleContent .= $user . ':<br><br>' . chr(13);
                        $peopleContent .= '<table cellspacing="0" cellpadding="0" width="800">
	<tr class="head">
            <td width="25%">Job</td>
            <td>Task</td>
            <td width="8%">完成度</td>
            <td width="10%">花费时间</td>
	</tr>'
                        ;
                        $cssClass = array('odd', 'even');
                        $j = 0;
                        foreach ($peopleItem as $jobKey => $jobItem) {
                            $i = 0;
                            $tdClass = $cssClass[$j % 2];
                            foreach ($jobItem as $taskKey => $taskItem) {
                                $peopleContent .= '<tr class="' . $tdClass . '">' . chr(13);
                                if ($i == 0) {
                                    $peopleContent .= '<td rowspan="' . count($jobItem) . '">' . $jobKey . '</td>' . chr(13);
                                }
                                $peopleContent .= '<td>' . $taskItem->taskdetail . '(' . $taskKey . ')</td>' . chr(13);
                                $peopleContent .= '<td>' . $taskItem->today_extra . '%</td>' . chr(13);
                                $peopleContent .= '<td>' . $taskItem->time_spent . '</td>' . chr(13);
                                $peopleContent .= '</tr>' . chr(13);
                                $i++;
                            }
                            $j++;
                        }
                        $peopleContent .= '</table><br><br>';
                    }
                    $people .= '<br>';

                    $content = '<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>morning report</title>
<style>
td {
	border:solid #68BADA;
	border-width:0px 1px 1px 0px;
	padding:5px;
}
table {
	border:solid #68BADA;
	border-width:1px 0px 0px 1px;
}
.odd{
	background:none repeat scroll 0 0 #E5F1F4;
}
.even{
	background:none repeat scroll 0 0 #F8F8F8;
}
.head{
	background:none repeat scroll 0 0 #90D8F0;
}
</style>
</head>
<body>';
                    $content .= 'Dear Paul,<br><br>' . chr(13);
                    $content .= date("m/d/Y") . '当班人员: ' . $people . ' 工作完成情况如下：<br><br>' . chr(13);
                    $content .= $peopleContent . '
谢谢。<br><br>

Task Management System
</body>
</html>
';
                    $emailInfo['content'] = $content;
                    $emailInfos[$key] = $emailInfo;
                    unset($people);
                    unset($peopleContent);
                    unset($content);
                    unset($emailInfo);
                }
            } else {
                $resultMsg = '没有任何人员的数据！';
            }
            //开始发信
            if ($emailInfos) {
                foreach ($emailInfos as $key => $emailInfo) {
                    $result = $this->sentEmail($emailInfo['email'], $emailInfo['title'], $emailInfo['content']);
                    if ($result['result']) {
                        $resultMsg .= $key . '部门晚报发送成功.<br>';
                    } else {
                        $resultMsg .= $key . '部门晚报发送成功：' . $result['error'] . '.<br>';
                    }
                }
            }
        } else {
            $resultMsg = '以下工作没有正常关闭，请核查.<br><br>' . $expireTask;
        }

        $this->render('message', array(
            'msg' => $resultMsg,
        ));
    }

    //发送邮件类
    protected function sentEmail($to, $title, $content, $att='') {
        set_time_limit(180);
        $message = new YiiMailMessage();

        $message->setContentType("text/html");
        $message->setTo(explode(',', $to));
        $message->setFrom(array('pds.task@gmail.com' => 'PDS Task'));
        $message->setSubject($title);
        $message->setBody($content);

        $result['result'] = true;
        try {
            Yii::app()->mail->send($message);
        } catch (Swift_ConnectionException $e) {
            $result['result'] = false;
            $result['error'] = 'There was a problem communicating with SMTP: ' . $e->getMessage();
        }
        return $result;
    }

    //所有人员的job
    public function actionJob() {
        $model = new PersonDate('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['PersonDate'])) {
            $model->attributes = $_GET['PersonDate'];
        }
        $jobStatus = (int) $_REQUEST['s'];
        $title = 'Job List';
        $this->render('jobAdmin', array(
            'model' => $model,
            'jobStatus' => $jobStatus,
            'title' => $title,
        ));
    }

    //自动关闭job，判断job下是否还有未完成的task，如果没有，job自动关闭
    function autoCloseJob($jobId) {
        $unDoneTasks = PersonTask::model()->findJobTask(0, $jobId); //搜索本job的未完成persontask
        if (!$unDoneTasks) {//没有未完成的task
            $criteria = new CDbCriteria;
            $criteria->addCondition('pdid=' . $jobId);
            if (PersonDate::model()->updateAll(array('status' => 1), $criteria)) {
                return true;
            } else {
                return false;
            }
        }
    }

}
